<?

function page_load ()
{	
   global $server;
   global $user;
   global $password;
   global $database;
   
	if (isset($HTTP_RAW_POST_DATA)) {                                                                                                                                  
		$input = $HTTP_RAW_POST_DATA;                                                                                                                                  
	} else if (strlen($HTTP_POST_VARS["input"])>0) {                                                                                                                                  
		$input = stripslashes($HTTP_POST_VARS["input"]);                                                                                                                                  
	} else {                                                                                                                                  
		$input = implode("\r\n", file('php://input'));                                                                                                                                  
	}

	$server    = $_GET["server"];
	$user      = $_GET["user"];
	$password  = $_GET["password"];
	$database  = $_GET["database"];
	
	if ($dom=domxml_open_mem($input))                                                                                                                                
	{  
        $o = $dom->document_element();  
		$path     = $o->get_attribute ('path'); 
		$server   = $o->get_attribute ('server');
		$user     = $o->get_attribute ('user');
		$password = $o->get_attribute ('password');
		$database = $o->get_attribute ('database');
		$pagesize = $o->get_attribute ('pagesize');
		$start    = $o->get_attribute ('start');
		if ($o->node_name() == 'create')
		{
			echo AddorModifyDatabase ($path, $server, $user, $password, $database);
			exit;
		}
	    
		if ($o->node_name() == 'backup')
		{  
		    $table = $o->get_content();
			echo OpenObject ('SELECT * FROM ' . $table, $start, $pagesize, './'.$table.'.backup.txt');
			exit;
		}
		if ($o->node_name() == 'remove')
		{  
			echo RemoveDatabase ($database);
			exit;
		}
		if ($o->node_name() == 'query')
		{
			if (strlen($pagesize)==0) $pagesize=100;
			$text=$o->get_content ();
			echo OpenObject ($text, $start, $pagesize);
			exit;
		}
	}
	
	$action    = $_GET["action"];
	$table	   = $_GET["table"];
	$start	   = $_GET["start"];
	$key	   = $_GET["key"];
	$path	   = $_GET["path"];
	$name	   = $_GET["name"];
	$value	   = $_GET["value"];
	
	if ($action=='persist')
	{ 
		echo Persist ($name, $value);
	}
	else if ($action=='getpersistance')
	{
		header ('Content-type: text/xml');
		echo GetPersistance ();
	}
	else if ($action=='getobjects')
	{
		header ('Content-type: text/xml');
		echo GetObjects ();
	}
	else if ($action=='getobject')
	{
		header ('Content-type: text/xml');
		echo GetObject ($table);
	}
	else if ($action=='getfeed')
	{ 
		echo implode ('', file ($path));
	}
	else if ($action=='getfile')
	{ 
		echo GetFile ($path);
	}
	else if ($action=='backupobject')
	{
	    echo OpenObject ('SELECT * FROM ' . $table, $start, 100, $path);
	}
	else if ($action=='openobject')
	{
		header ('Content-type: text/xml');
		echo OpenObject ('SELECT * FROM ' . $table, $start);
	}
	else if (strlen($action) > 0)
	{
		echo 'action "' . $action . '" not defined';
	}
}

page_load ();



function RemoveDatabase ($name)
{
    $message = array(); 
    $message[] = 'Looking up ' . $name;
    if ( $dom=domxml_open_file('application.xml') )
	{
	    foreach ($dom->get_elements_by_tagname('database') as $database)
        {
            if ($database->get_attribute ('name') == $name)
            { 
                $message[] = 'Deleting up ' . $name;
				$database->unlink_node (); 
            }
        } 
     
        $dom->dump_file ('application.xml');
         $message[] = 'Remove action succeeded!';
        return implode ("\n", $message);
	}
    return 'Could not open configuration file ' . $path;
}

function AddorModifyDatabase ($path, $server, $user, $password, $name)
{
    $message = array();
    $found = false;
    $message[] = 'Looking up ' . $name;
    if ( $dom=domxml_open_file('application.xml') )
	{
	    foreach ($dom->get_elements_by_tagname('database') as $database)
        {
            if ($database->get_attribute ('name') == $name)
            {
                $message[] = 'Updating ' . $name;
                $database->set_attribute ('server', $server);
                $database->set_attribute ('password', $password);
                $database->set_attribute ('username', $user);
                $found = true;
            }
        } 
    
        if (! $found )
        {
            $message[] = 'Adding ' . $name;
            $rootnode = $dom->document_element ();
            $database = $dom->create_element ('database');
            $database->set_attribute ('name', $name);
            $database->set_attribute ('server', $server);
            $database->set_attribute ('password', $password);
            $database->set_attribute ('username', $user);
            $rootnode->append_child ($database);
        }       
  
        $dom->dump_file ('application.xml');
         $message[] = 'Save action succeeded!';
        return implode ("\n", $message);
	}
    return 'Could not open configuration file ' . $path;
}

 
function Persist ($name, $value)
{
    setcookie($name, $value, time()+3600);
	return $name . ' was set to ' . $value;
} 

function GetPersistance ()
{
    $xml = array();
    $xml[] = '<persistance>'; 
    while(list ($name, $value)=each ($_COOKIE))  
    {
        $xml[] = '<add name="' . $name . '"><![CDATA['.$value.']]></add>'; 
    }
    $xml[] = '</persistance>';
    return implode ("\n", $xml);
} 

function GetFile ($path)
{	
	$docroot = $_SERVER['DOCUMENT_ROOT'];
    $address = $docroot . $path;
	$fp=fopen ($address, 'r');
	$fr=fread ($fp,filesize($address));
	fclose ($fp);
	return $fr;
}
  
function GetObjects ()
{ 
    global $database;
    $xml = array();
    $xml[] = '<!-- GetObjects ' . date ('m/d/Y H:i:s') . ' -->';
    $xml[] = '<tables database="' . $database . '">';
    $result = form_database_query("show table status");
    while($row = mysql_fetch_assoc($result))  
    {
        $xml[] = '<table ';
        $xml[] = ' name="' . $row['Name'] . '"';
        $xml[] = ' size="' . $row['Data_length'] . '"';
        $xml[] = ' type="' . $row['Type'] . '"';
        $xml[] = ' free="' . $row['Data_free'] . '"';
        $xml[] = ' created="' . $row['Create_time'] . '"';
        $xml[] = ' updated="' . $row['Update_time'] . '"';
        $xml[] = '/>';
    }
    $xml[] = '</tables>';
    return implode ("\n", $xml);
}


function GetObject ($table)
{
    global $database;
    $xml = array();
    $xml[] = '<table database="' . $database . '" name="' . $table . '">';
    $result = form_database_query("SHOW COLUMNS FROM $table"); 
    while($row = mysql_fetch_row($result))  
    {
        $xml[] = '<column';
        $xml[] = ' name="' . $row[0] . '"';
        $xml[] = ' type="' . $row[1] . '"';
        $xml[] = ' allownull="' . $row[2] . '"';
        $xml[] = ' key="' . $row[3] . '"';
        $xml[] = ' defaultvalue="' . $row[4] . '"';
        $xml[] = ' extra="' . $row[5] . '"';
        $xml[] = '/>';
    }
    $xml[] = '</table>';
    return implode ("\n", $xml);
}



function OpenObject ($query, $start=NULL, $pagesize=100, $backupas=NULL)
{
    global $database;
    $xml    = array();
    $name   = array();          
    $result = form_database_query($query); 
	if ($result)
	{
		$x      = mysql_num_fields($result);
		$count  = mysql_num_rows ($result);
		$affect = mysql_affected_rows ($result);
		$estart = microtime (true);
		$cursor = 1;
		
		if ($start && $start > 0 && $count > 0)
		{
			mysql_data_seek($result, $start);
		}
	 
        $xml[] = '<query><![CDATA['.$query.']]></query>';
		for ($i=0;$i<$x;$i++) $name[]=array ('name'=>mysql_field_name($result,$i),
											 'size'=>mysql_field_len($result,$i)	
											 );         
		while($row = mysql_fetch_row($result))  
		{
			$xml[] = '<record>';
			for ($i=0;$i<$x;$i++)
			{
			   $xml[]='<field name="' . $name[$i]['name'] . '" size="' . $name[$i]['size'] . '"><![CDATA[' . $row[$i] . ']]></field>';
			   if ($key==$name[$i]) $id=$row[$i];
			}
			$xml[] = '</record>';
			$cursor ++;
			if ($cursor > $pagesize) break;
		}
		$xml[] = '</recordset>';
		mysql_free_result($result);
		$exectime = microtime (true) - $estart;
		$output = '<recordset affect="'.$affect.'" elapsed="' . $exectime . '" database="' . $database . '" count="' . $count . '">' . implode ("", $xml);
		
		if ($backupas)
		{
		    $fp=fopen($backupas,'a');
			fwrite ($fp,$output);
			fclose ($fp);
		}
		return $output;
	}
	return '';
}


















$config    = "../mysql.config";
$req       = implode ('', file ($config)); 
$line      = explode ("\n", $req);
$limit     = sizeof($line); 
$i         = 0; 
$k         = 0;  
while ($i <= $limit) {	
	$t = trim($line[$i]);  
	parse_str($t);
	$i ++;
}
 



function generic_data($server,$user,$password,$database,$query) { 
    global $fatal;
	/* Accessing SQL-Server and querying table */ 
	MYSQL_CONNECT($server, $user, $password) or die ( $fatal." Server unreachable" );
	MYSQL_SELECT_DB($database) or die ( $fatal." Database unreachable" );  
	$result = @MYSQL_QUERY(stripslashes($query));
	if ($result)
	{
	}
	else
	{
		echo '<fault>';
		echo '<query><![CDATA[' . $query . ']]></query>';
		echo '<mysql_errno><![CDATA[' . mysql_errno() . ']]></mysql_errno>';
		echo '<mysql_error><![CDATA[' . mysql_error() . ']]></mysql_error>';
		echo '</fault>'; 
	} 	 
	return $result;  
	MYSQL_CLOSE();
}

function form_database_query($query) {
    
   global $server;
   global $user;
   global $password;
   global $database;
   return generic_data($server,$user,$password,$database,$query); 
} 

?>